package com.vcc.web.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckSafe;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.mybatisflex.core.paginate.Page;
import com.vcc.core.annotations.RestPack;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.model.file.cardOrder.CardOrderFilePojo;
import com.vcc.core.model.file.withdraw.WithdrawFilePojo;
import com.vcc.core.util.FileUtil;
import com.vcc.core.util.RegexUtil;
import com.vcc.data.entity.*;
import com.vcc.service.client.vo.cardOrder.CardOrderVo;
import com.vcc.service.service.BossUserService;
import com.vcc.service.service.CardOrderService;
import com.vcc.service.service.UserService;
import com.vcc.web.core.util.UserUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("cardOrder")
public class CardOrderController {

    @Resource
    private CardOrderService cardOrderService;
    @Resource
    private UserService userService;
    @Resource
    private BossUserService bossUserService;

    @GetMapping("paging")
    @SaCheckPermission(value = "card:order:view")
    @RestPack
    public Page<CardOrderVo> paging(
            Integer pageNumber,
            Integer pageSize,
            String orderId,
            Long cardTypeId,
            String type,
            String status,
            Long targetUserId,
            String cardNumber,
            String startDate,
            String endDate,
            Long userCardId
    ) {
        User user = UserUtil.get();
        Long parentId = user.getParentId();
        Role role = UserUtil.getRole();
        Page<CardOrderVo> paging = cardOrderService.paging(
                Page.of(pageNumber == null ? 1 : pageNumber, pageSize == null ? 20 : pageSize),
                role.getHasAllData() && parentId != null && parentId != 0 ? parentId : user.getId(),
                targetUserId,
                cardTypeId,
                orderId,
                null,
                role,
                type,
                status,
                cardNumber,
                StringUtils.isBlank(startDate) ? null : DateUtil.beginOfDay(DateUtil.parse(startDate, DatePattern.NORM_DATE_FORMAT)),
                StringUtils.isBlank(endDate) ? null : DateUtil.endOfDay(DateUtil.parse(endDate, DatePattern.NORM_DATE_FORMAT)),
                null,
                userCardId
        );
        if (paging.getRecords().isEmpty()) {
            return Page.of(
                    paging.getPageNumber(),
                    paging.getPageSize()
            );
        }
        List<CardOrderVo> records = paging.getRecords();
        List<Long> clientIds = records.stream().filter(it -> it.getOrderSource().equals("CLIENT")).map(CardOrderVo::getOperatorUserId).distinct().toList();
        List<Long> adminIds = records.stream().filter(it -> !it.getOrderSource().equals("CLIENT")).map(CardOrderVo::getOperatorUserId).distinct().toList();
        List<User> clientUsers = clientIds.isEmpty() ? List.of() : userService.listByIds(clientIds);
        List<BossUser> adminUsers = adminIds.isEmpty() ? List.of() : bossUserService.listByIds(adminIds);
        return paging.map(it -> {
            if (it.getOrderSource().equals("CLIENT")) {
                User clientUser = clientUsers.stream().filter(temp -> temp.getId().equals(it.getOperatorUserId())).findFirst().orElse(null);
                it.setOperatorAccount(clientUser != null ? clientUser.getAccount() : null);
            } else if (it.getOrderSource().equals("SYSTEM")) {
                BossUser bossUser = adminUsers.stream().filter(temp -> temp.getId().equals(it.getOperatorUserId())).findFirst().orElse(null);
                it.setOperatorAccount(bossUser != null ? bossUser.getAccount() : null);
            }
            return it;
        });
    }

    @GetMapping("derive")
    @SaCheckPermission(value = "card:order:derive")
    public void derive(
            String orderId,
            Long cardTypeId,
            String type,
            String status,
            Long targetUserId,
            String cardNumber,
            String startDate,
            String endDate,
            Long userCardId,
            HttpServletResponse response
    ) {
        User user = UserUtil.get();
        Long parentId = user.getParentId();
        Role role = UserUtil.getRole();
        if (RegexUtil.checkStringIsNull(startDate)) {
            throw new ProgramException("请选择开始时间");
        }
        if (RegexUtil.checkStringIsNull(endDate)) {
            throw new ProgramException("请选择结束时间");
        }
        Long pages = 1L;
        Page<CardOrderVo> paging;
        SXSSFWorkbook sxssfWorkbook = FileUtil.createCardOrderTitle(10000);
        do {
            paging = cardOrderService.paging(
                    Page.of(pages++, 1000),
                    role.getHasAllData() && parentId != null && parentId != 0 ? parentId : user.getId(),
                    targetUserId,
                    cardTypeId,
                    orderId,
                    null,
                    role,
                    type,
                    status,
                    cardNumber,
                    StringUtils.isBlank(startDate) ? null : DateUtil.beginOfDay(DateUtil.parse(startDate, DatePattern.NORM_DATE_FORMAT)),
                    StringUtils.isBlank(endDate) ? null : DateUtil.endOfDay(DateUtil.parse(endDate, DatePattern.NORM_DATE_FORMAT)),
                    null,
                    userCardId
            );
            List<CardOrderFilePojo> list = paging.getRecords().stream().map(it -> {
                return new CardOrderFilePojo(
                        it.getUserId(),
                        it.getAccount(),
                        it.getOperatorUserId(),
                        it.getOperatorAccount(),
                        it.getCardNumber(),
                        it.getCardNumberId() != null ? it.getCardNumberId().toString() : "",
                        it.getCardTypeId(),
                        it.getOrderNo(),
                        it.getOrderStatus(),
                        it.getOrderAmount(),
                        it.getOrderCurrency(),
                        it.getOrderType(),
                        DateUtil.format(it.getRequestTime(), DatePattern.NORM_DATETIME_FORMAT),
                        it.getCompleteTime() != null ? DateUtil.format(it.getCompleteTime(), DatePattern.NORM_DATETIME_FORMAT) : "",
                        it.getOrderRemark(),
                        it.getOrderSource()
                );
            }).collect(Collectors.toList());
            FileUtil.deriveCardOrderData(sxssfWorkbook, list, paging.getPageNumber(), paging.getPageSize());
        } while (!(pages).equals(paging.getTotalPage() + 1));
        String fileName = System.currentTimeMillis() + "入金明细.xlsx";
        FileUtil.downXlsxFile(response, sxssfWorkbook, fileName);
    }


}
